package main

import (
	"blog-backend/internal/config"
	"blog-backend/internal/routes"
	"blog-backend/pkg/auth"
	"blog-backend/pkg/database"
	"log"
	"os"

	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置
	config.LoadConfig()

	// 初始化JWT
	auth.InitJWT()

	// 初始化数据库
	database.InitDB()

	// 创建Gin实例
	router := gin.Default()

	// 添加 CORS 中间件（仅开发环境）
	if os.Getenv("ENV") == "development" {
		router.Use(func(c *gin.Context) {
			c.Writer.Header().Set("Access-Control-Allow-Origin", "http://127.0.0.1:8089")
			c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
			c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

			if c.Request.Method == "OPTIONS" {
				c.AbortWithStatus(204)
				return
			}

			c.Next()
		})
	}

	// 注册中间件
	router.Use(gin.Logger())
	router.Use(gin.Recovery())

	// 注册路由
	routes.RegisterAPIRoutes(router)

	// 启动服务器
	log.Printf("Server running on port %s", config.Cfg.ServerPort)
	router.Run(":" + config.Cfg.ServerPort)
}
